package com.tmsps.ne4weixin.api;

import com.alibaba.fastjson2.JSONObject;
import com.tmsps.ne4weixin.bean.qrcode.QrCode;
import com.tmsps.ne4weixin.bean.qrcode.vo.ActionInfo;
import com.tmsps.ne4weixin.bean.qrcode.vo.QrCodeVo;
import com.tmsps.ne4weixin.bean.qrcode.vo.SceneVo;
import com.tmsps.ne4weixin.config.WxConfig;
import com.tmsps.ne4weixin.config.enumeration.QRTypeEnum;
import com.tmsps.ne4weixin.utils.WXHttpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @Title: QrCodeAPI.java
 * @Package: com.tmsps.ne4weixin.api
 * @Description: 二维码管理API
 */
@Slf4j
public class QrCodeAPI extends BaseAPI {

	private String accessToken = null;
	
	public QrCodeAPI(WxConfig config) {
		super(config);
		this.accessToken = config.getAccessToken();
	}
	
	public QrCodeAPI(String accessToken) {
		super(null);
		this.accessToken = accessToken;
	}

	/**
	 * 创建临时二维码
	 * @param expire_seconds
	 * @param scene_id			场景值ID，临时二维码时为32位非0整型
	 * @return
	 */
	public QrCode createTemporary(Long expire_seconds, Integer scene_id) {
		QrCodeVo qrCodeVo = new QrCodeVo(expire_seconds, QRTypeEnum.QR_SCENE, new ActionInfo(new SceneVo(scene_id)));
		return this.created(qrCodeVo);
	}
	
	/**
	 * 创建临时二维码
	 * @param expire_seconds
	 * @param scene_str
	 * @return
	 */
	public QrCode createTemporary(Long expire_seconds, String scene_str) {
		QrCodeVo qrCodeVo = new QrCodeVo(expire_seconds, QRTypeEnum.QR_STR_SCENE, new ActionInfo(new SceneVo(scene_str)));
		return this.created(qrCodeVo);
	}
	
	/**
	 * 创建临时二维码
	 * @param scene_str			场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
	 * @return
	 */
	public QrCode createTemporary(String scene_str) {
		QrCodeVo qrCodeVo = new QrCodeVo(QRTypeEnum.QR_STR_SCENE, new ActionInfo(new SceneVo(scene_str)));
		return this.created(qrCodeVo);
	}
	
	/**
	 * 创建临时二维码
	 * @param scene_id			场景值ID，临时二维码时为32位非0整型
	 * @return
	 */
	public QrCode createTemporary(Integer scene_id) {
		QrCodeVo qrCodeVo = new QrCodeVo(QRTypeEnum.QR_SCENE, new ActionInfo(new SceneVo(scene_id)));
		return this.created(qrCodeVo);
	}

	/**
	 * 创建永久二维码
	 * @param scene_id			场景值ID,最大值为100000（目前参数只支持1--100000）
	 * @return
	 */
	public QrCode createdPermanent(Integer scene_id) {
		QrCodeVo qrCodeVo = new QrCodeVo(QRTypeEnum.QR_LIMIT_SCENE, new ActionInfo(new SceneVo(scene_id)));
		return this.created(qrCodeVo);
	}
	
	/**
	 * 创建永久二维码
	 * @param scene_str			场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
	 * @return
	 */
	public QrCode createdPermanent(String scene_str) {
		QrCodeVo qrCodeVo = new QrCodeVo(QRTypeEnum.QR_LIMIT_STR_SCENE, new ActionInfo(new SceneVo(scene_str)));
		return this.created(qrCodeVo);
	}
	
	private QrCode created(QrCodeVo qrCodeVo) {
		String url = String.format(CREATE, accessToken);
		String result = WXHttpUtil.postJson(url, JSONObject.toJSONString(qrCodeVo));
		log.info("创建二维码返回信息：{}", result);
		return JSONObject.parseObject(result, QrCode.class);
	}
}
